package org.viettan.android.main.managers;

import org.viettan.android.main.VietTanApplication;
import org.viettan.android.main.model.Language;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;

import com.google.common.base.Strings;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * Provides access to the user settings.
 */
@Singleton
public class SettingsManager {

    private final String GLOBAL_PREFERENCE_FILE = "VIETTAN_GLOBAL_SETTINGS";
    private Language articleLanguage = Language.ENGLISH;

    @Inject
    SettingsManager() {
    }

    /**
     * Loads all the settings from the permanent storage.
     */
    public void load() {
	String languageCode = get(Language.class.getSimpleName());
	if (!Strings.isNullOrEmpty(languageCode)) {
	    articleLanguage = Language.valueOf(languageCode);
	    updateUI(articleLanguage);
	}
    }

    /**
     * Returns the language of articles.
     */
    public Language getArticleLanguage() {
	return articleLanguage;
    }

    /**
     * Sets the language code for the articles.
     *
     * @param language
     */
    public void setArticleLanguage(Language language) {
	put(Language.class.getSimpleName(), language.name());
	this.articleLanguage = language;
	updateUI(articleLanguage);
    }

    private void updateUI(Language language) {
	Context context = VietTanApplication.getAppContext();
	Resources resources = context.getResources();
	DisplayMetrics metrics = resources.getDisplayMetrics();
	Configuration config = new Configuration(resources.getConfiguration());
	config.locale = language.getLocale();
	resources.updateConfiguration(config, metrics);
    }

    /**
     * Determines whether the last language is different from the current language.
     *
     * @param lastLanguage
     * @return
     */
    public boolean hasLanguageChanged(Language lastLanguage) {
	return articleLanguage != lastLanguage;
    }

    private void put(String key, String value) {
	Context context = VietTanApplication.getAppContext();
	SharedPreferences sharedPreference = context.getSharedPreferences(GLOBAL_PREFERENCE_FILE,
		Activity.MODE_PRIVATE);
	sharedPreference.edit().putString(key, value).commit();
    }

    private String get(String key) {
	Context context = VietTanApplication.getAppContext();
	SharedPreferences sharedPreference = context.getSharedPreferences(GLOBAL_PREFERENCE_FILE,
		Activity.MODE_PRIVATE);
	return sharedPreference.getString(key, null);
    }
}
